package com.gateway.plugin.resilience4j.handler;

import com.gateway.common.dto.RuleData;
import com.gateway.common.dto.convert.rule.Resilience4JHandle;
import com.gateway.common.enums.PluginEnum;
import com.gateway.common.utils.JsonUtils;
import com.gateway.plugin.base.cache.CommonHandleCache;
import com.gateway.plugin.base.handler.PluginDataHandler;
import com.gateway.plugin.base.util.BeanHolder;
import com.gateway.plugin.base.util.CacheKeyUtils;
import com.gateway.plugin.resilience4j.factory.Resilience4JRegistryFactory;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/24 09:59
 **/
public class Resilience4JHandler implements PluginDataHandler {
    public static final Supplier<CommonHandleCache<String, Resilience4JHandle>> CACHED_HANDLE = new BeanHolder<>(CommonHandleCache::new);

    @Override
    public void handlerRule(RuleData ruleData) {
        String key = CacheKeyUtils.INST.getKey(ruleData);
        Resilience4JRegistryFactory.remove(key);
        Optional.ofNullable(ruleData.getHandle())
                .ifPresent(handle -> {
                    Resilience4JHandle resilience4JHandle = JsonUtils.stringToBean(handle, Resilience4JHandle.class);
                    CACHED_HANDLE.get().cachedHandle(key, resilience4JHandle);
                });
    }

    @Override
    public void removeRule(RuleData ruleData) {
        String key = CacheKeyUtils.INST.getKey(ruleData);
        Resilience4JRegistryFactory.remove(key);
        Optional.ofNullable(ruleData.getHandle()).ifPresent(handle -> CACHED_HANDLE.get().removeHandle(key));
    }

    @Override
    public String pluginNamed() {
        return PluginEnum.RESILIENCE4J.getName();
    }
}
